package session.stateless;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entity.Log;
import entity.Employee;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Stateless
public class LogSessionBean implements LogSessionBeanLocal {

    @PersistenceContext
    private EntityManager entityManager;

    //Add Log
    @Override
    public void addLog(String type, String description, String page, String userId) {
        try {
            Employee employee=null;
            if (userId !=null)
             employee= entityManager.find(Employee.class, userId);
            
            Calendar cal = Calendar.getInstance();
            Timestamp ts = new Timestamp(cal.getTime().getTime());
            Log log = new Log(type, description, page, ts, employee);
          
            entityManager.persist(log);
            entityManager.flush();
        } catch (Exception ex) {
            System.out.println("Exception Message: " + ex.getMessage());
        }
    }

    @Override
    public List<Log> getLogs() {
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT l FROM Log l ORDER BY l.logDate DESC");

        for (Object o : query.getResultList()) {
            Log log = (Log) o;
            al.add(log);
        }

        return al;
    }

    @Override
    public List<String> getLogTypes() {
        ArrayList al = new ArrayList();

        Query query = entityManager.createQuery("SELECT DISTINCT l.type FROM Log l ORDER BY l.type ASC");

        for (Object o : query.getResultList()) {
            String s = (String) o;
            //System.out.println(s);
            al.add(s);
        }

        return al;
    }
}
